package com.macro.mall.portal.config.sharding.ranghash;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.macro.mall.portal.dao.ShardDao;
import com.macro.mall.portal.dao.ShardFragmentTableDao;
import com.macro.mall.portal.dao.ShardGroupDao;
import com.macro.mall.portal.domain.ShardNode;
import com.macro.mall.portal.domain.ShardFragmentTable;
import com.macro.mall.portal.domain.ShardGroup;
import org.springframework.boot.CommandLineRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wwj
 */
public class RangeHashShardInit implements CommandLineRunner {

    @Resource
    private ShardGroupDao shardGroupDao;
    @Resource
    private ShardDao shardDao;
    @Resource
    private ShardFragmentTableDao shardFragmentTableDao;



    @Override
    public void run(String... args) throws Exception {

        List<ShardGroup> shardGroupList = shardGroupDao.selectList(new QueryWrapper<ShardGroup>().eq("status", 1));

        List<ShardNode> shardNodeList = shardDao.selectList(new QueryWrapper<>());

        List<ShardFragmentTable> shardFragmentTableList = shardFragmentTableDao.selectList(new QueryWrapper<>());

        RangeHashProperties.shardGroupList = shardGroupList;
        RangeHashProperties.shardGroupNameMap = shardGroupList.stream().collect(Collectors.groupingBy(ShardGroup::getName));
        RangeHashProperties.shardNodeMap = shardNodeList.stream().collect(Collectors.groupingBy(ShardNode::getGroupShardId));
        RangeHashProperties.shardFragmentMap = shardFragmentTableList.stream().collect(Collectors.groupingBy(ShardFragmentTable::getShardId));
    }
}
